﻿namespace gisgeb.plugins.powershell
{
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Windows.Forms;

    using Microsoft.Win32;

    public static class PowerShellRunner
    {
        public static void OpenPowerShellAt(string dir)
        {
            RegistryKey hklm = Registry.LocalMachine;
            RegistryKey pshellEngineKey = hklm.OpenSubKey("Software\\Microsoft\\PowerShell\\1\\PowerShellEngine");
            if (pshellEngineKey == null)
            {
                MessageBox.Show(
                    "PowerShell-Installation could not be found...\nIf you feel this is a mistake please file a bug report.",
                    "PowerShell can not execute",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }

            var appBase = (string)pshellEngineKey.GetValue("ApplicationBase");
            var pshellExe = Path.Combine(appBase, "powershell.exe");


            ProcessStartInfo start = new ProcessStartInfo
                {
                    FileName = pshellExe, 
                    CreateNoWindow = false, 
                    UseShellExecute = true, 
                    WorkingDirectory = dir
                };

            Process p = new Process { StartInfo = start };
            p.Start();
        }
    }
}